package com.cxg.fairy.ec.detail;

import android.annotation.SuppressLint;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.ListViewCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.Toast;

import com.ToxicBakery.viewpager.transforms.DefaultTransformer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.cxg.fairy.app.AccountManager;
import com.cxg.fairy.app.Latte;
import com.cxg.fairy.delegates.LatteDelegate;
import com.cxg.fairy.net.RestClient;
import com.cxg.fairy.net.callback.ISuccess;
import com.cxg.fairy.ui.banner.HolderCreator;
import com.cxg.fairy.ui.recycler.MultipleItemEntity;
import com.cxg.fairy.util.log.LatteLogger;
import com.cxg.fairy.util.money.MoneyUtil;
import com.cxg.fairy.util.storage.LattePreference;
import com.diabin.latte.ec.R;
import com.diabin.latte.ec.R2;
import com.hedgehog.ratingbar.RatingBar;
import com.joanzapata.iconify.widget.IconTextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;

/**
 * Created by CFairy
 */

public class GoodsDetailDelegate extends LatteDelegate {

    @BindView(R2.id.detail_banner)
    ConvenientBanner<String> mBanner = null;

    @BindView(R2.id.scrollView_goods_detail)
    ScrollView mGoodsDetailsScrollView = null;

    @BindView(R2.id.tv_goods_info_title)
    AppCompatTextView mGoodsInfoTitle = null;
    @BindView(R2.id.tv_goods_info_desc)
    AppCompatTextView mGoodsInfoDesc = null;
    @BindView(R2.id.tv_goods_info_price)
    AppCompatTextView mGoodsInfoPrice = null;
    @BindView(R2.id.tv_goods_info_unit)
    AppCompatTextView mGoodsInfoUnit = null;
    @BindView(R2.id.tv_goods_info_real_unit)
    AppCompatTextView mGoodsInfoRealUnit = null;
    @BindView(R2.id.tv_goods_info_default_price)
    AppCompatTextView mGoodsInfoDefaultPrice = null;
    @BindView(R2.id.tv_goods_info_default_price_tag)
    AppCompatTextView mGoodsInfoDefaultPriceTag = null;
    @BindView(R2.id.tv_goods_info_already_sales_amount)
    AppCompatTextView mGoodsInfoAlreadySale = null;

    @BindView(R2.id.tv_goods_detail_comment_count)
    AppCompatTextView mGoodsCommentCount = null;
    @BindView(R2.id.tv_goods_detail_comment_mark)
    AppCompatTextView mGoodsAverageMark = null;
    @BindView(R2.id.rst_goods_detailcomment_start)
    RatingBar mRatingBar = null;

    @BindView(R2.id.frame_goods_comment_header)
    LinearLayoutCompat mFrameCommentHeader = null;

    @BindView(R2.id.rv_comment_list)
    ListViewCompat commentListView = null;

    //清单
    @BindView(R2.id.itv_add_favor_list)
    IconTextView mIconAddFavor = null;
    @BindView(R2.id.tv_add_favor_list)
    AppCompatTextView tvAddFavor = null;


    //底部
    private static final String ARG_GOODS_ID = "ARG_GOODS_ID";
    private int mGoodsId = -1;
    private String UUID = AccountManager.getSignUUID();
    String averageMark = Latte.getApplicationContext().getResources().getString(R.string.goods_detail_comment_rating);
    String commentCount = Latte.getApplicationContext().getResources().getString(R.string.goods_detail_comment_count);

    public static GoodsDetailDelegate create(int goodsId) {
        final Bundle args = new Bundle();
        args.putInt(ARG_GOODS_ID, goodsId);
        final GoodsDetailDelegate delegate = new GoodsDetailDelegate();
        delegate.setArguments(args);
        return delegate;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle args = getArguments();
        if (args != null) {
            mGoodsId = args.getInt(ARG_GOODS_ID);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_goods_detail;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initData();
        initCommentList();
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    private void initData() {
        RestClient.builder()
                .url("getGoodsDetail")
                .params("skuId",mGoodsId)
                .params("uuid", UUID)
                .loader(getContext())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        final JSONObject data = JSON.parseObject(response).getJSONObject("data");
                        initBanner(data);
                        final String name = data.getString("name");
                        final String desc = data.getString("description");
                        final String price = MoneyUtil.formatMoney(data.getDouble("price"));
                        final String unit = data.getString("unit");
                        final int sales = data.getIntValue("sale");
                        final String defaultPrice = MoneyUtil.formatMoney(data.getDouble("marketPrice"));

                        mGoodsInfoUnit.setText("/"+unit);
                        mGoodsInfoRealUnit.setText("/"+unit);
                        mGoodsInfoDefaultPrice.setText(defaultPrice);
                        mGoodsInfoDefaultPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                        mGoodsInfoDefaultPriceTag.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

                        mGoodsInfoAlreadySale.setText(getStr(R.string.goods_detail_sales) + sales);

                        mGoodsInfoTitle.setText(name);
                        mGoodsInfoDesc.setText(desc);
                        mGoodsInfoPrice.setText(price);

                    }
                })
                .build()
                .post();
    }

    private void initCommentList() {
            RestClient.builder()
                    .loader(getContext())
                    .url("getGoodsEvalByGoodsId_brief")
                    .params("uuid",AccountManager.getSignUUID())
                    .params("skuId",getArguments().getInt(ARG_GOODS_ID))
                    .success(new ISuccess() {
                        @SuppressLint("StringFormatMatches")
                        @SuppressWarnings("deprecation")
                        @Override
                        public void onSuccess(String response) {
                            List<MultipleItemEntity> data = new CommentListTopDataConverter().setJsonData(response).convert();
                            MultipleItemEntity headerEntity = new CommentListTopDataConverter().setJsonData(response).convertHeader();
                            final CommentListAdapter commentListAdapter = new CommentListAdapter(getContext(), R.layout.item_goods_detail_comment, data);
                            int averageStar = headerEntity.getField("ratingStar");
                            String averageStartStr = MoneyUtil.formatMoney(averageStar);
                            int mGoodsCommentCounts = headerEntity.getField("commentCount");
                            mGoodsAverageMark.setText(String.format(averageMark,averageStartStr));
                            mGoodsCommentCount.setText(String.format(commentCount,mGoodsCommentCounts));
                            mRatingBar.setStar(averageStar/2);
                            commentListView.setDividerHeight(0);
                            commentListView.setAdapter(commentListAdapter);
                            int height = 0;
                            int count = commentListAdapter.getCount();
                            for(int i=0;i<count;i++){
                                View temp = commentListAdapter.getView(i,null,commentListView);
                                temp.measure(0,0);
                                height += temp.getMeasuredHeight();
                            }
                            LinearLayoutCompat.LayoutParams params = (LinearLayoutCompat.LayoutParams) commentListView.getLayoutParams();
                            params.width = LinearLayoutCompat.LayoutParams.FILL_PARENT;
                            params.height = height;
                            commentListView.setLayoutParams(params);
                            commentListView.setFocusable(false);
                            mGoodsDetailsScrollView.smoothScrollTo(0, 20);
                        }
                    })
                    .build()
                    .post();
    }


    private void initBanner(JSONObject data) {
        final JSONArray array = data.getJSONArray("banners");
        final ArrayList<String> images = new ArrayList<>();
        final int size = array.size();
        for (int i = 0; i < size; i++) {
            images.add(array.getString(i));
        }
        mBanner.setPages(new HolderCreator(), images)
                .setPageIndicator(new int[]{R.drawable.dot_normal, R.drawable.dot_focus})
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setPageTransformer(new DefaultTransformer())
                .startTurning(3500)
                .setCanLoop(true);
    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        return new DefaultHorizontalAnimator();
    }

    public String getStr(int id) {
       return getResources().getString(id);
    }

}
